<?php

namespace app\admin\controller;

use app\common\controller\Backend;

use think\Controller;
use think\Request;
use think\Session;
use app\admin\model\HkStore as StoreModel;
use app\admin\model\StoreCat;
use app\mpbase\library\WechatApp;
use EasyWeChat\Core\Exceptions\HttpException;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use app\common\library\Distance;
use app\mpbase\library\WechatCard;
use app\admin\model\WechatCard as CardModel;
use com\qq\ai\Ai;


/**
 * 线下门店
 *
 * @icon fa fa-circle-o
 */
class Hkstore extends Backend
{
    
    /**
     * HkStore模型对象
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 's_name,s_address,check_data';

    public function _initialize()
    {
        parent::_initialize();
		//分类cat_id,name
		$catList = model('StoreCat')->column('id,cat_name');
		$areaList = model('CardArea')->column('id,area_name');
        $this->model = model('HkStore');
        $this->view->assign("statusList", $this->model->getStatusList());
		$this->view->assign("areaList",$areaList);
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                /*
                 * 已经弃用,如果为了兼容老版可取消注释
                  foreach ($params as $k => &$v)
                  {
                  $v = is_array($v) ? implode(',', $v) : $v;
                  }
                 */
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $disabled = '';
        $hidden = '';

        //判断是否为广告商或者商家、是否已经通过审核。部分字段不允许更改
        if((session('admin.type') != 0) && ($row['check_data'] == 1)){
            $disabled = 'disabled="disabled"';
            $hidden = 'style="display:none"';
        }

        $this->view->assign('disabled',$disabled);
        $this->view->assign('hidden',$hidden);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax())
        {
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('pkey_name'))
			{
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();


			$total = $this->model
				->where($where)
				->order($sort, $order)
				->count();

			$list = $this->model
				->where($where)
                ->order($sort, $order)
				->limit($offset, $limit)
                ->select();

			$result = array("total" => $total, "rows" => $list);
			return json($result);
		}
		return $this->view->fetch();
	}

	/**
	 * 添加
	 */
	public function add()
	{
		if ($this->request->isPost())
		{
			$params = $this->request->post("row/a");
			if ($params)
			{
				/*
				 * 已经弃用,如果为了兼容老版可取消注释
				  foreach ($params as $k => &$v)
				  {
				  $v = is_array($v) ? implode(',', $v) : $v;
				  }
				 */
				if ($this->dataLimit)
				{
					$params[$this->dataLimitField] = $this->auth->id;
				}
				// 应用数据限制
				if ($this->appletLimit)
				{
					$params['appletid'] = $this->appletLimit;
				}
				try
				{
					//是否采用模型验证
					if ($this->modelValidate)
					{
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
						$this->model->validate($validate);
					}
					$result = $this->model->allowField(true)->save($params);
					if ($result !== false)
					{
						$this->success();
					}
					else
					{
						$this->error($this->model->getError());
					}
				}
				catch (\think\exception\PDOException $e)
				{
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		return $this->view->fetch();
	}

	//生成小程序二维码 带店铺参数

	public function qrCode($ids)
	{
		$wechatApp = new \app\mpbase\library\QrCode();
		//首先判断该店铺是否生成了小程序码
		$storeModel = new StoreModel();
		$qrcode = $storeModel->where('id',$ids)->find();
		if(!$qrcode->qrcode){
			//不存在小程序码
			$file_name = mt_rand().'.jpg';
			$dir_name = ROOT_PATH.'qrcode/'.$file_name;
			$qrcode_name = $wechatApp->get_qrcode($dir_name,$ids,'pages/detail/index/index');
			$qrcode->qrcode = $file_name;
			$qrcode->save();
		}
		$this->assign('qrcode',config('qrcode').$qrcode->qrcode);
		return $this->view->fetch();
	}


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds))
            {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v)
            {
                $store_id = $v['id'];
                //删除商店下面的卡券,关联卡券 外键约束已经删除，发送请求微信后台卡券删除
                $cardmodel = new CardModel();
                $wechatCard = new WechatCard();
                $cat_list = $cardmodel->getStoreCard($store_id);
                foreach($cat_list as $key => $val){
                    $wechatCard->delete($val);
                }
                $count += $v->delete();
            }
            if ($count)
            {
                $this->success();
            }
            else
            {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


	//判断是否在区域内
	public function distance()
	{
		//深圳经纬度范围
        $sz_arr = [
			['lng' => 113.659548 , 'lat' => 22.895433],
			['lng' => 113.92322 , 'lat' => 22.388455],
			['lng' => 114.719729 , 'lat' => 22.424004],
			['lng' => 114.430308 , 'lat' => 23.039577],
		];

		//青岛经纬度范围
		$qd_arr = [
			['lng' => 119.30 , 'lat' => 37.09],
			['lng' => 119.30 , 'lat' => 35.35],
			['lng' => 121.00 , 'lat' => 37.09],
			['lng' => 121.00 , 'lat' => 35.35]
		];

		//北京经纬度范围
		$bj_arr = [
			['lng' => 115.7 , 'lat' => 41.6],
			['lng' => 115.7 , 'lat' => 39.4],
			['lng' => 117.4 , 'lat' => 39.4],
			['lng' => 117.4 , 'lat' => 41.6]
		];

		$point = ['lng' => '113.896502', 'lat' => '22.440036'];
//		113.896502,22.440036
		$result = Distance::isPointInPolygon($sz_arr,$point);
		dump($result);
	}

    //获取距离
    public function test()
    {
        $options = [
            'appid'=>'1106881821', //填写调用接口的appid
            'app_key'=>'ybDDM1KEtptwmqih' //填写调用接口的密钥
        ];
        $ai = new Ai($options);
        $path = './uploads/00000001/20180327/a89992fc6c50ed4681e3b16ecbb163c1.png';
        $data = file_get_contents($path);
        $base64 = base64_encode($data);
        $json = $ai->vision_porn($base64);
        dump($json);

    }
	/**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
